/**
 * Created by ss on 16/3/29.
 */
var logHelper = require("./../log4jsHelper.js");
var data = require("./../data.json");
var url = require("url");

function cb(req, res, next){
	try{
		var result = new Array();
		var urlParse = url.parse(req.url, true);
		switch(urlParse.pathname){
			case "/province":
				for(var i = 0, l = data.length; i < l ; i++){
					var item = data[i];
					result.push(item.name);
				}
				break;
			case "/city":
				var provinceName = decodeURIComponent(urlParse.query.proName);
				var chooseItem = null;
				chooseItem = findProvince(provinceName);
				if( chooseItem ){
					for(var i = 0 ; i < chooseItem.city.length ; i++){
						var item = chooseItem.city[i];
						result.push(item.name);
					}
				}
				break;
			case "/county":
				var provinceName = decodeURIComponent(urlParse.query.proName);
				var cityName = decodeURIComponent(urlParse.query.cityName);
				var chooseItem = findProvince(provinceName);
				chooseItem = findCity(chooseItem, cityName);
				result = chooseItem.area;
				break;
			default :
				break;
		}
		res.writeHead(200, {"Content-Type": "text/html;charset:utf-8"});
		res.end(JSON.stringify(result));
	}catch(e){
		logHelper.debug(JSON.stringify(e));
	}finally{
		next();
	}

}

function findProvince(proName){
	var chooseItem = null;
	for(var i = 0, l = data.length; i < l ; i++){
		var item = data[i];
		if(proName == item.name){
			chooseItem = item;
			break;
		}
	}
	return chooseItem;
}

function findCity(chooseItem, cityName){
	for(var i = 0, l = chooseItem.city.length; i < l; i++){
		var item = chooseItem.city[i];
		if(cityName == item.name){
			return item;
		}
	}
}

module.exports = cb;